<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-10-23
 * Time: 00:13
 */

namespace app\api\controller;
use app\common\controller\ApiController;
use think\Db;
class Vehicle extends ApiController
{

    function __construct(){
        parent::__construct();
    }

    // 车辆列表
    public function getList() {
        $param = $this->request->param();
        $where[] = ['c.is_deleted','=',0];
        if(!empty($param['name'])) $where[] = ['c.name','like','%'.$param['name'].'%'];
        if(!empty($this->userinfo['cm_message_id'])){
            if (@$param['cm_message_id']) {
                $where[] = ['bd.id','in',$param['cm_message_id']];
            } else {
                $where[] = ['bd.id','in',$this->userinfo['cm_message_id']];
            }
        }
        $list = Db::name('wy_car c')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->leftJoin('wy_car_area a','c.car_area_id = a.id')
            ->where($where)
            ->field('c.*,bd.name bd_name,a.name car_area_name')
            ->page($param['pageNo'],$param['pageSize'])
            ->order('c.id','desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['bz_number'] = Db::name('wy_toll_bz_middle')->alias('m')
                ->join('wy_toll_project p','m.project_id = p.id')
                ->join('wy_toll_project_detial d','m.project_detail_id = d.id')
                ->where(['houses_id'=>$v['id'],'type'=>3])->count();
        }
        $count = Db::name('wy_car c')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->where($where)->count();
            // echo Db::name('wy_car')->getlastsql();die;
        return __success('ok',['data'=>$list,'pageSize'=>$param['pageSize'],'pageNo'=>$param['pageNo'],'totalCount'=>$count,'totalPage'=>ceil($count / $param['pageSize'])]);
    }

    // 添加or编辑车辆
    public function operation() {
        $param = $this->request->param();
        unset($param['token']);
        if($param['send'] === 'first'){
            if(empty($param['bd_info_id'])) return __error('所属小区不可为空');
            if(empty($param['name'])) return __error('车牌号码不可为空');
            // 查询车牌、停车卡号信息->防止车牌、停车卡号重复
            $carMap[] = ['is_deleted','=',0];
            if($param['id'] !== 0) $carMap[] = ['id','<>',$param['id']];
            $nameInfo = Db::name('wy_car')->where($carMap)->where('name',$param['name'])->find();
            if(!empty($nameInfo) && $param['id'] == 0) return __error('车牌重复');
            if(@$param['stop_numbers']){
                $stopNumbersInfo = Db::name('wy_car')->where($carMap)->where('stop_numbers',$param['stop_numbers'])->find();
                if(!empty($stopNumbersInfo) && $param['id'] == 0) return __error('停车卡号重复');
            }
        }
        if($param['id'] == 0){
            $id = Db::name('wy_car')->strict(false)->insert($param,true,true);
            return __success('添加成功',$id);
        }else{
            unset($param['send']);
            $upRes = Db::name('wy_car')->update($param);
            return $upRes !== false ? __success('保存成功',$param['id']) : __error('保存失败');
        }
    }

    // 删除车辆
    public function delVehicle() {
        $ids = $this->request->param('ids');
        if(empty($ids)) return __error('参数错误');
        // 判断当前车辆下是否有住户
//        $user = Db::name('wy_houses_user_middle')->alias('m')->join('wy_car c','m.car_id = c.id')->where('m.car_id','in',$ids)->select();
//        foreach ($user as $key=>$value){
//            return __error('车辆' . $value['name'] . '存在住户,不可删除');
//        }
        $delRes = Db::name('wy_houses_user_middle')->where('car_id','in',$ids)->delete();
        if(empty($delRes)) return __error('住户解绑失败');
        $upRes = Db::name('wy_car')->where('id','in',$ids)->update(['is_deleted'=>1,'car_area_id'=>null]);
        return $upRes !== false ? __success('删除成功') : __error('删除失败');
    }

    // 绑定用户
    public function bindUser() {
        $param = $this->request->param();
        $data = array();
        foreach ($param['house_user_id'] as $key=>$value) array_push($data,['house_user_id'=>$value,'car_id'=>$param['car_id'],'middle_type'=>3]);
        $findIsBind = Db::name('wy_houses_user_middle')->where(['house_user_id'=>['in',implode(',',$param['house_user_id'])],'car_id'=>$param['car_id']])->find();
        if(!empty($findIsBind)) return __error('请勿重复绑定');
        $addRes = Db::name('wy_houses_user_middle')->insertAll($data);
        return $addRes ? __success('绑定成功') : __error('绑定失败');
    }
    // 获取小区车辆
    public function getVehicleTree(){
        $param = $this->request->param();
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        if($this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $communityList = Db::name('wy_bd_info')->where($where)->field('id value,name label')->select();
        
        $communityIds = array();
        foreach ($communityList as $key=>$value) array_push($communityIds,$value['value']);
        // 车位
        $carList = Db::name('wy_car')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id')->select();
        // 拼装数据
        $allData = array();
        foreach ($communityList as $ck=>$cv){
            $cv['children'] = array();
            $cv['title']=$cv['label'];
            $cv['key']=$cv['value'];
            foreach ($carList as $bk=>$bv){
                $bv['title']=$bv['label'];
                $bv['key']=$bv['value'];
                if($bv['bd_info_id'] === $cv['value']) {
                    unset($bv['bd_info_id']);
                    array_push($cv['children'],$bv);
                }
            }
            if(!empty($cv['children'])) array_push($allData,$cv);
        }
        return __success('ok',$allData);
    }

    // 获取可绑定住户
    public function getBindUserList() {
        $id = $this->request->param('id'); // 车辆id
        $bd_info_id = $this->request->param('bd_info_id'); // 小区id
        $text = $this->request->param('text'); // 搜索
        $type = intval($this->request->post('type'));
        if(empty($text)) return __success('ok',[]);
        if(mb_strlen($text) < 2) return __success('ok',[]);
        // 当前车辆已关联住户
        $middleUser = Db::name('wy_houses_user_middle')->where('car_id',$id)->column('house_user_id');
        $map = 'status in(1,4)';
        if(!empty($middleUser)){
            $map .= ' and id not in ('.implode(',',$middleUser).')';
        }
        if ($text) {
            if ($type == 1) {
                $map .= ' and (license like \''.$text.'%\' )';
            } else {
                $hids = Db::name('wy_houses')->where('name','like','%'.$text.'%')->column('id');
                if ($hids) {
                    $map .= ' and (phone like \''.$text.'%\' or name like \''.$text.'%\' or houses_id in ('.implode(',',$hids).'))';
                } else {
                    $map .= ' and (phone like \''.$text.'%\' or name like \''.$text.'%\' )';
                }
            }
        }
        $list = Db::name('wy_house_user')->where($map)->field('id value,bd_info_id,building_id,houses_id,name,phone,status')->limit(20)->group('phone')->order('houses_id desc')->select();
        foreach ($list as $key=>$value){
            $bd_info_text = Db::name('wy_bd_info')->where('id',$value['bd_info_id'])->value('name');
            // $building_text = Db::name('wy_building')->where('id',$value['building_id'])->value('name');
            $houses_text = Db::name('wy_houses')->where('id',$value['houses_id'])->value('name');
            if ($value['status'] == 4) {
                $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
            } else {
                if($bd_info_text && $houses_text){
                    $list[$key]['label'] =  $bd_info_text.'-'.$houses_text.'-'.$value['name'].'-'.$value['phone'];
                }else{
                    $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
                }
            }
        }
        return __success('ok',$list);
    }

    // 获取车辆信息
    public function getInfo() {
        $id = $this->request->param('id');
        if(empty($id)) return __error('参数错误');
        $info = Db::name('wy_car c')
            ->join('wy_bd_info b','c.bd_info_id = b.id')
            ->leftJoin('wy_car_area a','c.car_area_id = a.id')
            ->leftJoin('wy_labels l','c.labels_id = l.id')
            ->where('c.id',$id)->field('c.*,b.name bd_name,a.name car_area_name,l.name label_name')->find();
        if(!empty($info['car_img'])) {
            $where = ['id'=>$info['car_img']];
            $info['car_img'] = model('wy_imgs')->getImgsList($where);
        }else $info['car_img'] = [];
        if(!empty($info['car_license'])) {
            $where = ['id'=>$info['car_license']];
            $info['car_license'] = model('wy_imgs')->getImgsList($where);
        }else $info['car_license'] = [];
        if(!empty($info['user_driver'])) {
            $where = ['id'=>$info['user_driver']];
            $info['user_driver'] = model('wy_imgs')->getImgsList($where);
        }else $info['user_driver'] = [];
        // 相关住户
        $houseUser = Db::name('wy_houses_user_middle')->alias('m')
            ->join('wy_house_user u','m.house_user_id = u.id')
            ->join('wy_bd_info bd','u.bd_info_id = bd.id')
            ->join('wy_building b','u.building_id = b.id')
            ->join('wy_unit un','u.unit_id = un.id')
            ->join('wy_houses h','u.houses_id = h.id')
            ->leftJoin('wy_labels l','u.labels_id = l.id')
            ->where(['m.car_id'=>$info['id']])->field('u.id,u.name,u.phone,bd.name bd_name,b.name building_name,un.name unit_name,h.name houses_name,l.name label_name')->order('m.id desc')->select();
        // 相关车位
        $carArea = Db::name('wy_car_area')->alias('a')
            ->join('wy_bd_info b','a.bd_info_id = b.id')
            ->leftJoin('wy_labels l','a.labels_id = l.id')
            ->where(['a.id'=>$info['car_area_id']])->field('a.id,a.name,b.name bd_name,l.name label_name')->select();
        // 相关收费标准
        $tollBz = Db::name('wy_toll_bz_middle')->alias('m')
            ->join('wy_toll_project p','m.project_id = p.id')
            ->join('wy_toll_project_detial d','m.project_detail_id = d.id')
            ->where(['m.houses_id'=>$id,'type'=>3])
            ->field('m.id,p.name project_name,d.name project_detail_name,DATE_FORMAT(m.start_time,"%Y-%m-%d") start_time,DATE_FORMAT(m.end_time,"%Y-%m-%d") end_time,m.is_have_time,m.remarks')->select();
        foreach ($tollBz as $key=>$value){
            if($value['is_have_time'] === 1) $tollBz[$key]['end_time'] = '无结束时间';
        }
        return __success('ok',['data'=>$info,'house_user'=>$houseUser,'car_area'=>$carArea,'bz'=>$tollBz]);
    }

    // 解绑用户
    public function untiedUser() {
        $car_id = $this->request->param('car_id'); // 车辆id
        $house_user_id = $this->request->param('house_user_id'); // 住户id
        if(empty($car_id)) return __error('参数错误');
        if(empty($house_user_id)) return __error('参数错误');
        $delRes = Db::name('wy_houses_user_middle')->where(['car_id'=>$car_id,'house_user_id'=>$house_user_id])->delete();
        return !empty($delRes) ? __success('解绑成功') : __error('解绑失败');
    }

    // 获取小区对应车位
    public function getCarAreaList() {
        $bdInfoId = $this->request->param('bd_info_id');
        if(empty($bdInfoId)) return __error('参数错误');
        $list = Db::name('wy_car_area')->where('bd_info_id',$bdInfoId)->field('id value,name label')->select();
        return __success('ok',$list);
    }

    // 获取小区车辆
    public function getAllCommunityVehicle() {
        $param = $this->request->param();
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        if($this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $communityList = Db::name('wy_bd_info')->where($where)->field('id value,name label')->select();
        $communityIds = array();
        foreach ($communityList as $key=>$value) {
            array_push($communityIds,$value['value']);
            $communityList[$key]['id']=$value['value'];
        }
        // 车辆
        $vehicleList = Db::name('wy_car')->where('bd_info_id','in',$communityIds)->field('id value,name label,bd_info_id')->select();
        foreach ($communityList as $ck=>$cv){
            $communityList[$ck]['children'] = array();
            $communityList[$ck]['value'] = $ck.'-'.$cv['value'];
            foreach ($vehicleList as $pk=>$pv){
                if($pv['bd_info_id'] === $cv['value']){
                    unset($pv['bd_info_id']);
                    array_push($communityList[$ck]['children'],$pv);
                }
            }
        }
        return __success('ok',$communityList);
    }

    // 获取车辆为缴费账单
    public function get_car_detail_nopay() {
        $param = $this->request->post();
        $data = Db::name('wy_no_payment')->where(['car_id' => $param['id'], 'pay_status' => 0])->select();
        $typetext = ['1' => '房屋', '2' => '车辆', '3' => '车位', '4' => '住户'];
        if(empty($data)) {
            return __error('暂无数据');
        } else {
            foreach($data as $k => $v) {
                $data[$k]['car_name'] = Db::name('wy_car')->where('id', $v['car_id'])->value('name');
                $data[$k]['type'] = $typetext[$v['type']];
            }
            return __success('查询成功', $data);
        }
    }

}